package com.wyd.tool;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;

public class MyTemplate {
	Map<String, Object> rootMap = new HashMap<>();
	String templatePath = null;
	String templateFile = null;
	File myFile = null;

	public MyTemplate(Map<String, Object> rootMap, String templatePath, String templateFile, File myFile) {
		super();
		this.rootMap = rootMap;
		this.templatePath = templatePath;
		this.templateFile = templateFile;
		this.myFile = myFile;
	}

	public void generat(boolean overRide) {
		Configuration cfg = new Configuration();
		try {
			File fltFiles = new File(templatePath);
			if (!fltFiles.exists()) {
				System.out.println("模板文件夹不存在！");
				return;
			}
			cfg.setDirectoryForTemplateLoading(fltFiles);
			cfg.setObjectWrapper(new DefaultObjectWrapper());
			Template template = cfg.getTemplate(templateFile);

			if (myFile.exists() && !overRide) {
				return;
			}
			if (!myFile.getParentFile().exists()) {
				myFile.mkdirs();
			}
			if (myFile.exists()) {
				myFile.delete();
			}
			myFile.createNewFile();
			OutputStream outputStream = new FileOutputStream(myFile);
			Writer out = new OutputStreamWriter(outputStream,"UTF-8");
			template.process(rootMap, out);
			out.flush();
			out.close();
			outputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected static void createDir(File file) throws IOException {
		if (!file.exists()) {
			file.getParentFile().mkdirs();
			file.createNewFile();
		}
	}
}
